// pages/goodsManagement/goodsManagementIndex.js
const controllers = require('../../controllers/controllerIndex.js').controller;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    labels: [],
    multiIndex: [0, 0],
    rightList: [],
    labelId: 0,
    navchoice: -1,
    imgurl: 'test',
    showActionsheet: true,
    groups: [
      ['自定义添加商品', '选择模板'],
      ["商品"]
    ],
    multiArray: [
      ['自定义添加商品', '选择模板'],
      ['商品']
    ],
    show: false,
    type: 0,
    isCustom: false,
    isshow: false,
    modeltype: 1,
    isHiddenSel: true,
    isHiddenManage: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    var that = this
    controllers.selectLabel({
      type: 1, //0默认1商城页面分类列表2店铺入驻分类列表3系统新增商城分类
      shopId: wx.getStorageSync('shopId'),

    }).then(res => {
      let navchoice = this.data.navchoice
      // if(res.data&&res.data.length>0){
      //    navchoice= -1
      // }
      let labels = []
      labels.push({
        name: '全部',
        id: -1
      })
      labels.push({
        name: '平台推荐',
        id: '平台推荐'
      })
      labels.push({
        name: '门店推荐',
        id: '门店推荐'
      })
      labels = labels.concat(res.data)
      that.setData({
        labels: labels,
        navchoice: navchoice
      })
      that.getProduct(navchoice)
    })
  },
  onloaddata() {
    var that = this
    controllers.selectLabel({
      type: 1, //0默认1商城页面分类列表2店铺入驻分类列表3系统新增商城分类
      shopId: wx.getStorageSync('shopId'),

    }).then(res => {
      let navchoice = that.data.navchoice
      // if(res.data&&res.data.length>0){
      //    navchoice= -1
      // }
      let labels = []
      labels.push({
        name: '全部',
        id: -1
      })
      labels.push({
        name: '平台推荐',
        id: '平台推荐'
      })
      labels.push({
        name: '门店推荐',
        id: '门店推荐'
      })
      labels = labels.concat(res.data)
      that.setData({
        labels: labels,
        navchoice: navchoice
      })
      that.getProduct(navchoice)
    })
    // var that =this
    // controllers.selectLabel({
    //   type: 1,//0默认1商城页面分类列表2店铺入驻分类列表3系统新增商城分类
    //   shopId:wx.getStorageSync('shopId'),

    // }).then(res =>{
    //   let navchoice=''
    //   if(res.data&&res.data.length>0){
    //      navchoice= res.data[0].id
    //   }

    //  that.setData({
    //   labels:res.data,
    //   navchoice:navchoice
    //   })
    //   that.getProduct(res.data[0].id)
    // })
  },
  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  setUporLo(res) {
    console.log(res)
    var that = this
    var state = res.currentTarget.dataset.state;
    var id = res.currentTarget.dataset.id;

    if (this.data.navchoice == '门店推荐' || this.data.navchoice == '平台推荐') {
      if (state == 0) {
        that.setCloudLowp(id);
      } else {
        that.setCloudUp(id);
      }

      return
    }
    controllers.setGoodsState({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      goodsId: id,
      state: state == 0 ? 1 : 0
    }).then(res => {
      if (state == '0') {
        wx.showToast({
          title: '下架成功',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '上架成功',
          icon: 'none',
          duration: 2000
        })
      }

      let index = that.data.rightList.findIndex(item => {
        return item.id == id;
      });
      let nowList = that.data.rightList;
      nowList[index].state = state == 0 ? 1 : 0
      that.setData({
        rightList: nowList
      })

    })
  },
  handleShowManage() {
    this.setData({
      isHiddenSel: !this.data.isHiddenSel
    })
  },
  handleBatchGoods(e) {
    const index = e.currentTarget.dataset.index;
    let rightList = this.data.rightList
    rightList[index].selset = !rightList[index].selset
    this.setData({
      rightList
    })
  },

  handleBatchLow() {

  },
    
  // 批量处理商品
  setBatchGoods(e) {
    const that = this
    var state = e.currentTarget.dataset.state;
    let goodsIds = []
    this.data.rightList.forEach(item => {
      if (item.selset) {
        goodsIds.push(item.id)
      }
    })
    if (goodsIds.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
      return
    }
    goodsIds = goodsIds.join(",")

    if(typeof state == "number"){
      this.batchSetGoodsState(goodsIds,state)
    }else{
      wx.showModal({
        title: '删除',
        content: '是否删除',
        success (res) {
          if (res.confirm) {
            that.handleBatchDelete(goodsIds)
          } 
        }
      })
    }

  },
  // 批量设置商品状态（上下架）
  batchSetGoodsState(goodsIds,state) {
    // state:0上架1下架
    controllers.batchSetGoodsState({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      goodsIds,
      state
    }).then(res => {
      if (state == '1') {
        wx.showToast({
          title: '下架成功',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '上架成功',
          icon: 'none',
          duration: 2000
        })
      }
      const rightList = this.data.rightList
      rightList.forEach(item1 => {
        goodsIds.split(",").forEach(item2 => {
          if (item1.id == item2)item1.state = state
        })
      });
      this.setData({
        rightList
      })
    })
  },
  // 批量删除商品
  handleBatchDelete(goodsIds) {
    controllers.batchDelGoods({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      goodsIds,
    }).then(res => {
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000
      })
      this.getProduct(this.data.navchoice)

    })
  },
  setCloudUp(id) {

    var that = this

    controllers.setCloudUp({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      goodsId: id

    }).then(res => {
      wx.showToast({
        title: '上架成功',
        icon: 'none',
        duration: 2000
      })

      //    rightList: res.data.list

    })
  },
  setCloudLowp(id) {
    var that = this
    controllers.setCloudLow({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      goodsId: id

    }).then(res => {
      wx.showToast({
        title: '下架成功',
        icon: 'none',
        duration: 2000
      })
      //    rightList: res.data.list
    })
  },

  navchoice(e) {
    let isHiddenManage = false
    const id = e.currentTarget.id
    if (id == '平台推荐' || id == '门店推荐') {
      isHiddenManage = true
    }
    this.setData({
      navchoice: id,
      pageNumber: 1,
      scrollTop: 0,
      isHiddenManage
    })
    this.getProduct(id);
  },

  getProduct(labelId, page) {

    var page = page || 1
    var that = this
    var jsonInfo = {
      pageSize: 20,
      pageNumber: page,
    }


    if (labelId == '平台推荐') {
      controllers.recommendCloutGoodsPage(jsonInfo).then(res => {
        let rightList = that.data.rightList
        for (let item of res.data.list) {
          item.commend = 1
        }
        if (page != 1) {
          rightList = rightList.concat(res.data.list)
        } else {
          rightList = res.data.list
        }
        that.setData({
          rightList: rightList,
          jsonInfo: jsonInfo,
          lastPage: res.data.lastPage,
          pageNumber: res.data.pageNumber,
          totalRow: res.data.totalRow
        })
      })
    } else if (labelId == '门店推荐') {
      jsonInfo.shopId = wx.getStorageSync('shopId')
      controllers.shopRecommendCloutGoodsPage(jsonInfo).then(res => {
        let rightList = that.data.rightList
        for (let item of res.data.list) {
          item.commend = 1
        }
        if (page != 1) {
          rightList = rightList.concat(res.data.list)
        } else {
          rightList = res.data.list
        }
        that.setData({
          rightList: rightList,
          jsonInfo: jsonInfo,
          lastPage: res.data.lastPage,
          pageNumber: res.data.pageNumber,
          totalRow: res.data.totalRow
        })
      })
    } else {
      jsonInfo.shopId = wx.getStorageSync('shopId')
      if (labelId != -1) {
        jsonInfo.labelId = labelId
      }


      controllers.shopLabelGoodsPage(jsonInfo).then(res => {

        let rightList = that.data.rightList
        if (page != 1) {
          rightList = rightList.concat(res.data.list)

        } else {

          rightList = res.data.list
        }

        that.setData({
          rightList: rightList,
          jsonInfo: jsonInfo,
          lastPage: res.data.lastPage,
          pageNumber: res.data.pageNumber,
          totalRow: res.data.totalRow
        })
      })
    }
  },
  lower(e) {
    let that = this
    if (!that.data.lastPage) {
      let p = that.data.pageNumber
      that.getProduct(that.data.navchoice, p + 1)
    }
  },
  //跳转编辑
  toComfirmOrder(e) {
    let type = e.currentTarget.dataset['type'];
    let id = e.currentTarget.dataset['id'];
    let commend = e.currentTarget.dataset['commend'];
    if (commend == 1) {
      wx.navigateTo({
        url: '/pages/goodsManagement/addGoods/addGoods?type=' + type + '&id=' + id + '&isedit=0',
      })
    } else {
      wx.navigateTo({
        url: '/pages/goodsManagement/addGoods/addGoods?type=' + type + '&id=' + id,
      })
    }

  },
  //  弹窗选项
  bindPickerChange(e) {
    console.log(e)
    if (this.data.isCustom) {
      this.setData({
        show: true,
        modeltype: e.detail.value[1] == 0 ? 1 : 0
      })
    } else {
      if (e.detail.value[0] == 0) {
        if (this.data.labels.length <= 3) {
          wx.showToast({
            title: '请先添加分类',
          })
          return
        }
        wx.navigateTo({
          url: '/pages/goodsManagement/addGoods/addGoods?type=1' + '&isAddGoods=' + true,
        })
      }
    }
  },

  bindcolumnchange(e) {
    console.log("e", e.detail)
    let isCustom
    let groups = this.data.groups



    var data = {
      isCustom: this.data.isCustom,
      groups: this.data.groups,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.isCustom = false
            data.groups[1] = ['商品'];
            break;
          case 1:
            data.isCustom = true
            data.groups[1] = ['选择模板导入'];
            break;
        }
        data.multiIndex[1] = 0;
        break;
    }

    this.setData(data);





  },

  // 跳转搜索
  goodsSearch() {
    wx.navigateTo({
      url: '../goodsSearch/goodsSearch',
    })
  },

  // 跳转排序页面
  sort() {

    let listString = JSON.stringify(this.data.rightList);
    let jsonInfo = JSON.stringify(this.data.jsonInfo);

    wx.navigateTo({
      url: '../goodsSort/goodsSort?listString=' + listString + '&jsonInfo=' + jsonInfo,
    })
  },

  // 跳转分类管理页面
  classifcation() {
    wx.navigateTo({
      url: '../classification/classification',
    })
  },


  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {

    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = ['服务', '商品'];
            break;
          case 1:
            data.multiArray[1] = ['选择商品模板', '选择服务模板'];
            break;
        }
        data.multiIndex[1] = 0;
        break;
    }

    this.setData(data);
  },
  //授权获取通知
  getNotice() {
    wx.requestSubscribeMessage({
      tmplIds: ['xuswtoB5eb-45E7Yg-Kir8I0TvPy4rNqq45N23phnJg', 'xj5_icSoClP-NuaWvNaJyScXDdcO6HURWeMegK4xQuA', 'XDClVimBX4BrOEHUmhI284E5OQLlxWG92a074pAjShY'],
      success: res => {
        console.log(res);
      }
    })
  }
})